<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="userId">
        <el-select size="small" v-model="queryParams.userId" placeholder="请选择用户名称" clearable filterable>
          <el-option v-for="(dict,index) in userList" :key="index" :label="dict.userName" :value="dict.userId"/>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="店铺" prop="storeId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.storeId"-->
      <!--          placeholder="请输入店铺id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeUserRelateList" @selection-change="handleSelectionChange"
              :tree-props="{children: 'storeGradRelateList'}" row-key="id" border stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户名" prop="userName" width="300">
        <template slot-scope="scope">
          <span class="text-info">
            {{ scope.row.userName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="产品ID" align="center" prop="storeName">
        <template slot-scope="scope">
          <div>
            {{ scope.row.aeProductId }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="产品类型" align="center">
        <template slot-scope="scope">
          <div>
            <dict-tag :options="dict.type.erp_product_type" :value="scope.row.type"></dict-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="提成分配" align="center">
        <template slot-scope="scope">
          <div v-if="!scope.row.storeGradRelateList">
            <div>{{ scope.row.gradRate + '%提成' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.storeGradRelateList">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户店铺维护关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名称" prop="userId">
          <el-select size="small" v-model="form.userId" placeholder="请选择用户名称" clearable filterable>
            <el-option v-for="(dict,index) in userList" :key="index" :label="dict.userName" :value="dict.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="产品配置">
          <div v-for="(item,storeIndex) in form.storeGradRelateList">
            <div class="flex">
              <div class="mr10">
                <el-select size="small" v-if="item.type" v-model="item.type.toString()" placeholder="请选择产品类型"
                           clearable
                           filterable>
                  <el-option v-for="(dict,index) in dict.type.erp_product_type" :key="index" :label="dict.label"
                             :value="dict.value"/>
                </el-select>
              </div>
              <div class="mt5">
                <el-input placeholder="请输入产品ID" size="small" v-model="item.aeProductId">
                  <el-button slot="append" size="mini" @click="getProductList(item.aeProductId)">查询</el-button>
                </el-input>
              </div>
              <div class="mt5 ml10">
                <el-input placeholder="请输入比例" size="small" v-model="item.gradRate">
                  <template slot="append">%提成</template>
                </el-input>
              </div>
            </div>
            <el-divider></el-divider>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="flex-between">
          <div>
            <el-button size="small" :loading="buttonLoading" type="primary" @click="addStore">增加产品</el-button>
            <el-button size="small" :loading="buttonLoading" type="danger" @click="cutStore">删除产品</el-button>
          </div>
          <div>
            <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm">确定</el-button>
            <el-button size="small" @click="cancel">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <!--  商品图片弹窗  -->

  </div>
</template>

<script>
import {
  listProductUserRelate,
  getProductUserRelate,
  delProductUserRelate,
  addProductUserRelate,
  updateProductUserRelate, getProductList, getErpUserList
} from "@/api/commission/commission";

export default {
  name: "StoreUserRelate",
  dicts: ['erp_product_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户店铺维护关联表格数据
      storeUserRelateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        storeId: undefined,
      },
      // 表单参数
      form: {
        storeGradRelateList: [{
          "type": '1',
          "gradRate": '',
          'aeProductId': ''
        }]
      },
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户不能为空", trigger: "change"}
        ],
        storeId: [
          {required: true, message: "店铺不能为空", trigger: "change"}
        ],
        commission: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
      },
      productList: [],//店铺列表
      userList: [],//用户列表

    };
  },
  created() {
    this.getList();
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    getUserList() {
      getErpUserList().then(res => {
        this.userList = res.data.sysUserList
      })
    },
    // 获取店铺账号选择列表
    getProductList(id) {
      console.log('id', id)
      this.loading = true;
      getProductList({aeProductId: id}).then(res => {
        this.productList = res.data.empowerList;
        this.loading = false;
      });
    },
    // 确定提成分配
    submitCommission(item) {
      console.log('item', item)
    },
    // 增加店铺
    addStore() {
      let length = this.form.storeGradRelateList.length
      // if (length < 5) {
        this.form.storeGradRelateList.push({
          "type": '1',
          "gradRate": '',
          'aeProductId': ''
        })
      // } else {
      //   this.$message.info('数量已达上限！')
      // }
    },
    // 减少店铺
    cutStore() {
      let length = this.form.storeGradRelateList.length
      if (length > 1) {
        this.form.storeGradRelateList.splice(length - 1, 1)
      } else {
        this.$message.info('请至少保留1条！')
      }
    },
    /** 查询用户店铺维护关联列表 */
    getList() {
      this.loading = true;
      listProductUserRelate(this.queryParams).then(response => {
        this.storeUserRelateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        storeGradRelateList: [{
          'aeProductId': '',
          "gradRate": '',
          'type': '1'
        }],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户商品提成配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getProductUserRelate(id).then(response => {
        this.loading = false;
        this.form = response.data;
        // let list = response.data.storeGradRelateList
        // for (let i = 0; i < list.length; i++) {
        //   list[i].type = list[i].type.toString()
        // }
        this.form.oldUserId = response.data.userId
        this.open = true;
        this.title = "修改用户商品提成配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.storeGradRelateList.some((val) => val.type == '')) {
            this.$message.error('请选择产品类型！')
            return
          }
          if (this.form.storeGradRelateList.some((val) => val.aeProductId == '')) {
            this.$message.error('产品ID不能为空！')
            return
          }
          if (this.form.storeGradRelateList.some((val) => val.gradRate == '')) {
            this.$message.error('提成比例不能为空！')
            return
          }
          console.log('this.foerm', this.form)
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateProductUserRelate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addProductUserRelate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userId || this.ids;
      this.$modal.confirm('是否确认删除该用户数据？').then(() => {
        this.loading = true;
        return delProductUserRelate(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('seller/storeUserRelate/export', {
        ...this.queryParams
      }, `storeUserRelate_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
